import { _decorator, Animation, Component, EventMouse, Input, input, Node, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerController')
export class PlayerController extends Component {
	private _curPos: Vec3 = new Vec3()
	private _targetPos: Vec3 = new Vec3()
    private _stepLength: number = 40
    private _startJump: boolean = false;
    private _jumpTimer: number = 0;
    private _stepTime: number = 0.2;
    private _jumpSpeed: number = 0;


    @property(Animation)
    public bodyAnim: Animation = null;
    
    
    private _totalResultScore:number = 0;

	start() {
		
    }
    
    checkIsCanController(value:boolean) {
        if (value) {
            input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this)
        } else {
           input.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this)
        }
    }

    onMouseDown(event: EventMouse) {
        console.log("onMouseDown")
		if (event.getButton() === EventMouse.BUTTON_LEFT) {
			this.jumpByStep(1)
		} else if (event.getButton() === EventMouse.BUTTON_RIGHT) {
			this.jumpByStep(2)
		}
	}

    jumpByStep(step: number) {
        if (this._startJump) {
            return
        }
        const cartoon = step === 1 ? "jumpOneStep" : "jumpTwoStep";
        const animState = this.bodyAnim.getState(cartoon)
        this._stepTime = animState.duration;
        this._startJump = true
        this._curPos = this.node.position
        this._jumpSpeed = step * this._stepLength / this._stepTime;


		this._targetPos = new Vec3(
			this._curPos.x + step * this._stepLength,
			this._curPos.y,
			this._curPos.z
        )
        this.bodyAnim.play(cartoon)
        this._totalResultScore += step;
	}


	update(deltaTime: number) {
        if (this._startJump) {
            this._jumpTimer += deltaTime;
            if (this._jumpTimer > this._stepTime) {
                this._jumpTimer = 0;
                this._startJump = false;
                this.node.setPosition(this._targetPos)
                this.node.emit("jumpEnd", this._totalResultScore);
            } else {
                this.node.setPosition(this._curPos.x + deltaTime * this._jumpSpeed,this._curPos.y,this._curPos.z)
            }
         
            
            
        }
		
    }
    
    playerReset() {
        this.node.setPosition(0, 0, 0)
        this._totalResultScore = 0;
    }

	onDestroy() {
		input.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this)
	}
}


